package com.net.wheels;

import com.google.common.base.Charsets;
import com.google.common.io.Files;
import org.apache.commons.collections.CollectionUtils;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 2019/4/17 11:01

 */
public class FileJoiner {

    public static void main(String[] args) throws IOException {
        createShardSql();
        createCommonSql();
    }

    private static void createShardSql() throws IOException {
        String projectPath = System.getProperty("user.dir");
        String fileDir = projectPath + "/updates/shard";

        File file = new File(fileDir);
        StringBuilder text = new StringBuilder();
        AtomicInteger counter = new AtomicInteger();
        joinerFileContent(file, text, counter);
        System.out.println(text);
        File file1 = new File(projectPath  + "/shard.sql");
        Files.write(text.toString().getBytes(), file1);
    }

    private static void createCommonSql() throws IOException {
        String projectPath = System.getProperty("user.dir");
        String fileDir = projectPath + "/updates/common";

        File file = new File(fileDir);
        StringBuilder text = new StringBuilder();
        AtomicInteger counter = new AtomicInteger();
        joinerFileContent(file, text, counter);
        System.out.println(text);
        File file1 = new File(projectPath  + "/common.sql");
        Files.write(text.toString().getBytes(), file1);
    }

    private static void joinerFileContent(File file, StringBuilder text, AtomicInteger counter) throws IOException {
        if (file.isDirectory()) {
            File[] fileList = file.listFiles();
            if (fileList != null && fileList.length != 0) {
                for (File f : fileList) {
                    joinerFileContent(f, text, counter);
                }
            }
        } else {
            counter.getAndIncrement();
            List<String> lines = Files.readLines(file, Charsets.UTF_8);
            if (CollectionUtils.isNotEmpty(lines)) {
                lines.forEach(line -> {
                    text.append(line).append("\n");
                });
            }
        }


    }
}

